/**
 * May 5, 2014 4:57:04 PM
 */
package elitech.vietnam.copyweatherfashion.fragments;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import org.xmlpull.v1.XmlPullParserException;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.koushikdutta.urlimageviewhelper.UrlImageViewHelper;

import elitech.vietnam.copyweatherfashion.CreatePostActivity;
import elitech.vietnam.copyweatherfashion.LoginActivity;
import elitech.vietnam.copyweatherfashion.MainActivity;
import elitech.vietnam.copyweatherfashion.R;
import elitech.vietnam.copyweatherfashion.adapters.CommentAdapter;
import elitech.vietnam.copyweatherfashion.config.Const;
import elitech.vietnam.copyweatherfashion.dialog.ConfirmDialogFragment;
import elitech.vietnam.copyweatherfashion.dialog.ConfirmDialogFragment.ConfirmDialogClick;
import elitech.vietnam.copyweatherfashion.dialog.ConfirmDialogFragment.Type;
import elitech.vietnam.copyweatherfashion.dialog.WarningDialogFragment.OnButtonClick;
import elitech.vietnam.copyweatherfashion.dialog.WarningDialogFragment;
import elitech.vietnam.copyweatherfashion.entities.Comment;
import elitech.vietnam.copyweatherfashion.entities.Member;
import elitech.vietnam.copyweatherfashion.utilities.MyCallable;
import elitech.vietnam.copyweatherfashion.widget.ButtonFriend;
import elitech.vietnam.copyweatherfashion.widget.ButtonLike;
import elitech.vietnam.copyweatherfashion.widget.ExpandableHeightListView;
import elitech.vietnam.copyweatherfashion.widget.ScaleImageView;
import elitech.vietnam.copyweatherfashion.wsclient.Service;

/**
 * @author Cong
 */
public class MemberPostFragment extends MyAbstractFragment implements View.OnClickListener, ConfirmDialogClick, OnButtonClick {

	private static final int	TASKS		= 2;
	public static final String	ARGS_POSTID	= "ARGS_POSTID";
	
	/**
	 * Request code for warning dialog to pop back stack
	 */
	public static final int		REQUEST_POPBACK = 1;

	MainActivity				mActivity;

	Member						mMember;

	ImageView					mImgAvatar;
	ScaleImageView				mImgContent;
	TextView					mTxtName, mTxtProfile, mTxtCmtCount, mTxtContent, mTxtComment;
	ImageButton					mBtnComment;
	ButtonFriend				mBtnFriend;
	ButtonLike					mBtnLike;
	ExpandableHeightListView	mLvComment;
	ArrayList<Comment>			mCmtList	= new ArrayList<>();
	CommentAdapter				mAdapter;
	EditText					mEdtComment;

	int							mPostId		= -1;
	int							mTask		= 0;

	public static MemberPostFragment newInstance(int idPost) {
		MemberPostFragment fragment = new MemberPostFragment();
		Bundle bundle = new Bundle();
		bundle.putInt(ARGS_POSTID, idPost);
		fragment.setArguments(bundle);
		return fragment;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mActivity = (MainActivity) getActivity();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.member_post, container, false);

		mImgAvatar = (ImageView) view.findViewById(R.id.mempost_imgAvatar);
		mImgContent = (ScaleImageView) view.findViewById(R.id.mempost_imgContent);
		mTxtName = (TextView) view.findViewById(R.id.mempost_txtName);
		mTxtProfile = (TextView) view.findViewById(R.id.mempost_txtProfile);
		mBtnFriend = (ButtonFriend) view.findViewById(R.id.mempost_btnFriend);
		mTxtCmtCount = (TextView) view.findViewById(R.id.mempost_txtCmtCount);
		mLvComment = (ExpandableHeightListView) view.findViewById(R.id.mempost_lvComment);
		mTxtContent = (TextView) view.findViewById(R.id.mempost_txtContent);
		mBtnLike = (ButtonLike) view.findViewById(R.id.mempost_btnLike);
		mBtnComment = (ImageButton) view.findViewById(R.id.mempost_btnComment);
		mEdtComment = (EditText) view.findViewById(R.id.mempost_edtComment);

		mLvComment.setExpanded(true);
		mAdapter = new CommentAdapter(mActivity, R.layout.layout_comment, mCmtList);
		mLvComment.setAdapter(mAdapter);

		mBtnFriend.setOnClickListener(this);
		mImgContent.setOnClickListener(this);
		mBtnComment.setOnClickListener(this);
		mBtnLike.setOnClickListener(this);

		return view;
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		mPostId = (getArguments() != null) ? getArguments().getInt(ARGS_POSTID, -1) : -1;
		if (mActivity.mStylePost == null && mPostId <= 0)
			throw new NullPointerException("Must set MainActivity mShopPost or ARGS_POSTID first");
	}
	
	@Override
	public void onStart() {
		super.onStart();
		/*
		 * Initialize header view
		 */
		mActivity.mBtnBack.setVisibility(View.VISIBLE);
		mActivity.mBtnNotify.setVisibility(View.GONE);
		/*
		 * Initialize main view
		 */
		if (mPostId <= 0) {
			mTask = 0;
			new GetMember().execute();
			new GetComment().execute();

			UrlImageViewHelper.setUrlDrawable(mImgContent, Const.SERVER_IMAGE_URL + mActivity.mStylePost.Image);
			mTxtContent.setText(mActivity.mStylePost.Content);
			mTxtCmtCount.setText(mActivity.mStylePost.Comments + "");
			mBtnLike.setData(mActivity.mStylePost.Liked(), mActivity.mStylePost.Likes);
		} else
			new GetPost().execute(mPostId);
	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();
	}

	@Override
	public void onClick(View v) {
		/**
		 * Hide keyboard
		 */
		InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(mActivity.getWindow().getCurrentFocus().getWindowToken(), 0);
		switch (v.getId()) {
		/**
		 * Add friend request, execute FriendCommand task No need to check if
		 * friend has been added, if the button show, it means this friend not
		 * added
		 */
		case R.id.mempost_btnFriend:
			new FriendCommand().execute();
			break;
		/**
		 * When click on post's image, let the image zoom-able
		 */
		case R.id.mempost_imgContent:
			mActivity.getCurrentBase().replaceFragment(
					ZoomPagerItemFragment.newInstance(Const.SERVER_IMAGE_URL + mActivity.mStylePost.Image), true);
			break;
		/**
		 * Click comment event
		 */
		case R.id.mempost_btnComment:
			/**
			 * If user not logged in, open LoginActivity, else execute
			 * NewComment task
			 */
			if (mActivity.mUser == null) {
				Intent intent = new Intent(mActivity, LoginActivity.class);
				mActivity.startActivityForResult(intent, MainActivity.REQUEST_LOGIN);
			} else if (mEdtComment.getText().toString().length() != 0) {
				new NewComment().execute();
			}
			break;
		case R.id.mempost_btnLike:
			if (mActivity.mUser == null) {
				Intent intent = new Intent(mActivity, LoginActivity.class);
				mActivity.startActivityForResult(intent, MainActivity.REQUEST_LOGIN);
			} else {
				final String ms = (mActivity.mStylePost.Liked()) ? mActivity
						.getString(R.string.do_you_want_to_unlike_this_post_) : mActivity
						.getString(R.string.do_you_want_to_like_this_post_);
				new ConfirmDialogFragment.Builder().setMessage(ms)
						.setType(Type.FRAGMENT).setTargetFragment(this).build()
						.show(mActivity.getSupportFragmentManager());
			}
			break;
		default:
			break;
		}
	}

	@Override
	public void onResume() {
		super.onResume();
		/**
		 * Implement onActivityResult Base on MainActivity.mRequestCode and
		 * MainActivity.mResultIntent
		 */
		if (mActivity.mRequestCode == MainActivity.REQUEST_LOGIN && mActivity.mResultIntent != null) {
			mActivity.getLoggedMemberInfo(mActivity.mResultIntent.getIntExtra(LoginActivity.EXTRA_USERID, -1),
					new MyCallable() {
						@Override
						public void call() {
							mActivity.mBtnCamera.setVisibility((mActivity.mUser != null) ? View.VISIBLE : View.GONE);
							mActivity.mBtnNotify.setVisibility((mActivity.mUser != null) ? View.VISIBLE : View.GONE);
							new GetPost().execute(mActivity.mStylePost.Id);
							mActivity.mRequestCode = -1;
							mActivity.mResultIntent = null;
						}
					});
		}
		if (mActivity.mRequestCode == MainActivity.REQUEST_EDITPOST) {
			mPostId = mActivity.mResultIntent.getIntExtra(CreatePostActivity.EXTRA_POSTID, 0);
			new GetPost().execute(mActivity.mStylePost.Id);
			mActivity.mRequestCode = -1;
			mActivity.mResultIntent = null;
		}
	}

	private void finishLoading() {
		mTask += 1;
		if (mTask == TASKS)
			showMain();
	}

	class GetMember extends AsyncTask<Integer, Integer, Member> {
		@Override
		protected void onPreExecute() {
			mActivity.mBtnCamera.setVisibility(View.GONE);
			mActivity.mBtnEdit.setVisibility(View.GONE);
			if (mMain.getVisibility() != View.GONE)
				showLoading();
		}

		@Override
		protected Member doInBackground(Integer... params) {
			try {
				return new Service().getInfoMemberById(mActivity.mStylePost.StoreId, (mActivity.mUser == null) ? -1
						: mActivity.mUser.Id);
			} catch (IOException | XmlPullParserException e) {
				e.printStackTrace();
				return null;
			}
		}

		@Override
		protected void onPostExecute(Member result) {
			if (!isVisible())
				return;
			if (result == null) {
				new WarningDialogFragment.Builder().setMessage(getString(R.string.cannot_connect_to_server)).build()
						.show(getFragmentManager());
			} else {
				mMember = result;
				UrlImageViewHelper.setUrlDrawable(mImgAvatar, Const.SERVER_IMAGE_THUMB_URL + mMember.Image,
						R.drawable.avatar);
				mTxtName.setText(mMember.Name);
				mTxtProfile.setText(mMember.Profile);

				if (mActivity.mUser != null && mActivity.mUser.Id != mMember.Id) {
					mBtnFriend.setStatus(mMember.Friend == 1);
					mBtnFriend.setVisibility(View.VISIBLE);
					mActivity.mBtnEdit.setVisibility(View.GONE);
					mActivity.mBtnCamera.setVisibility(View.VISIBLE);
				} else {
					mBtnFriend.setVisibility(View.GONE);
					mActivity.mBtnEdit.setVisibility(mActivity.mUser != null ? View.VISIBLE : View.GONE);
					mActivity.mBtnCamera.setVisibility(mActivity.mUser != null ? View.GONE : View.VISIBLE);
				}

				mActivity.mTxtTitle.setText(Html.fromHtml(getString(R.string.stylertitle).replace(
						getString(R.string.styler), getString(R.string.style)).replace("TODAY", mMember.Name)));
			}
			finishLoading();
		}
	}

	class GetComment extends AsyncTask<Integer, Integer, ArrayList<Comment>> {
		@Override
		protected void onPreExecute() {
			if (mMain.getVisibility() != View.GONE)
				showLoading();
		}

		@Override
		protected ArrayList<Comment> doInBackground(Integer... params) {
			try {
				return new Service().getListCommentPost(mActivity.mStylePost.Id, 0, 10);
			} catch (IOException | XmlPullParserException e) {
				e.printStackTrace();
				return null;
			}
		}

		@Override
		protected void onPostExecute(ArrayList<Comment> result) {
			if (!isVisible())
				return;
			if (result == null) {
				new WarningDialogFragment.Builder().setMessage(getString(R.string.cannot_connect_to_server)).build()
						.show(getFragmentManager());
			} else if (result.isEmpty()) {
			} else {
				mCmtList.clear();
				mCmtList.addAll(result);
				mAdapter.notifyDataSetChanged();
			}
			finishLoading();
		}
	}

	class GetMoreComment extends AsyncTask<Integer, Integer, ArrayList<Comment>> {
		@Override
		protected void onPreExecute() {
		}

		@Override
		protected ArrayList<Comment> doInBackground(Integer... params) {
			return null;
		}

		@Override
		protected void onPostExecute(ArrayList<Comment> result) {
		}
	}

	class FriendCommand extends AsyncTask<Integer, Integer, Boolean> {
		@Override
		protected void onPreExecute() {
			mBtnFriend.setEnabled(false);
		}

		@Override
		protected Boolean doInBackground(Integer... params) {
			try {
				return new Service().follow(mActivity.mUser.Id, mMember.Id) > 0;
			} catch (IOException | XmlPullParserException e) {
				e.printStackTrace();
				return null;
			}
		}

		@Override
		protected void onPostExecute(Boolean result) {
			if (!isVisible())
				return;
			mBtnFriend.setEnabled(true);
			if (result == null) {
				new WarningDialogFragment.Builder().setMessage(getString(R.string.cannot_connect_to_server)).build()
						.show(getFragmentManager());
			} else {
				mMember.Friend = result ? 1 : 0;
				mBtnFriend.setStatus(result);
				if (result) {
					new AsyncTask<Integer, Integer, Boolean>() {
						@Override
						protected Boolean doInBackground(Integer... params) {
							try {
								new Service().notifyFriendAdd(mActivity.mUser.Id, mMember.Id);
							} catch (IOException | XmlPullParserException e) {
								e.printStackTrace();
							}
							return null;
						}
					}.execute();
				}
			}
		}
	}

	class GetPost extends AsyncTask<Integer, Integer, Boolean> {
		@Override
		protected void onPreExecute() {
			if (mMain.getVisibility() != View.GONE)
				showLoading();
		}

		@Override
		protected Boolean doInBackground(Integer... params) {
			try {
				mActivity.mStylePost = new Service().getPostByID(params[0],
						(mActivity.mUser != null) ? mActivity.mUser.Id : -1, Const.COUNTRYCODE);
			} catch (IOException | XmlPullParserException e) {
				return false;
			}
			return true;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			if (!isVisible())
				return;
			if (!result) {
				new WarningDialogFragment.Builder().setMessage(getString(R.string.cannot_connect_to_server)).build()
						.show(getFragmentManager());
			} else if (mActivity.mStylePost.Status == 1) {
				mTask = 0;
				new GetMember().execute();
				new GetComment().execute();

				UrlImageViewHelper.setUrlDrawable(mImgContent, Const.SERVER_IMAGE_URL + mActivity.mStylePost.Image);
				mTxtContent.setText(mActivity.mStylePost.Content);
				mTxtCmtCount.setText(mActivity.mStylePost.Comments + "");
				mBtnLike.setData(mActivity.mStylePost.Liked(), mActivity.mStylePost.Likes);
			} else {
//				new WarningDialogFragment.Builder().setMessage(getString(R.string.stylehasbeendeleted))
//				.setTargetFragment(MemberPostFragment.this, REQUEST_POPBACK).build()
//				.show(getFragmentManager());
				showText(getString(R.string.stylehasbeendeleted));
			}
		}
	}

	class NewComment extends AsyncTask<Integer, Integer, Boolean> {
		String content = "";
		int rs = -1;
		@Override
		protected void onPreExecute() {
			content = mEdtComment.getText().toString();
			mEdtComment.setText("");
		}

		@Override
		protected Boolean doInBackground(Integer... params) {
			try {
				rs = new Service().newComment(mActivity.mUser.Id, mActivity.mStylePost.Id, content);
				return rs > 0;
			} catch (IOException | XmlPullParserException e) {
				e.printStackTrace();
				return false;
			}
		}

		@Override
		protected void onPostExecute(Boolean result) {
			if (!isVisible())
				return;
			if (!result) {
				Toast.makeText(mActivity, R.string.cannot_connect_to_server, Toast.LENGTH_SHORT).show();
			} else {
				Comment comment = new Comment();
				comment.Id = rs;
				comment.Content = content;
				comment.Image = mActivity.mUser.Image;
				comment.MemberId = mActivity.mUser.Id;
				comment.MemId = mActivity.mUser.Username;
				comment.Name = mActivity.mUser.Name;
				comment.PostId = mActivity.mStylePost.Id;
				comment.Status = 1;
				comment.CMID = "";
				comment.Date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", mActivity.getCurrentLocale()).format(new Date());
				mCmtList.add(comment);
				mAdapter.notifyDataSetChanged();
				mTxtCmtCount.setText((mActivity.mStylePost.Comments += 1) + "");
				new AsyncTask<Integer, Integer, Boolean>() {
					@Override
					protected Boolean doInBackground(Integer... params) {
						try {
							new Service().notifyComment(rs);
						} catch (IOException | XmlPullParserException e) {
							e.printStackTrace();
						}
						return null;
					}
				}.execute();
			}
		}
	}

	class LikeTask extends AsyncTask<Integer, Integer, Integer> {
		@Override
		protected void onPreExecute() {
			mBtnLike.setEnabled(false);
		}

		@Override
		protected Integer doInBackground(Integer... params) {
			try {
				return new Service().newLike(mActivity.mUser.Id, mActivity.mStylePost.Id,
						mActivity.mStylePost.Liked() ? -1 : 1);
			} catch (IOException | XmlPullParserException e) {
				e.printStackTrace();
				return null;
			}
		}

		@Override
		protected void onPostExecute(Integer result) {
			if (!isVisible())
				return;
			mBtnLike.setEnabled(true);
			if (result == null || result == -1) {
				new WarningDialogFragment.Builder().setMessage(getString(R.string.cannot_connect_to_server)).build()
						.show(getFragmentManager());
			} else {
				mActivity.mStylePost.Liked(!mActivity.mStylePost.Liked());
				mActivity.mStylePost.Likes = result;
				mBtnLike.setData(mActivity.mStylePost.Liked(), mActivity.mStylePost.Likes);
			}
		}
	}

	@Override
	public void yesClick() {
		new LikeTask().execute();
	}

	@Override
	public void noClick() {
	}

	@Override
	public void doClick(int requestCode) {
		switch (requestCode) {
		case REQUEST_POPBACK:
			mActivity.getCurrentBase().popAllFragment();
			break;
		default:
			break;
		}
	}
}
